package com.wxg.my.d01;

public class DaemonPrinterV2 {

    public static void main(String[] args) throws InterruptedException {
        DaemonPrinterV2.forClass(daemonPrinterV2.getClass())
                .setInterval(800);

        for (int i = 0; i < 10; i++) {
            System.out.println(String.valueOf(System.currentTimeMillis()).substring(7));
            Thread.sleep(1000);
        }
    }

    public static DaemonPrinterV2 forClass(Class<?> clazz) {
        daemonPrinterV2.setClazz(clazz);
        return daemonPrinterV2;
    }

    public static DaemonPrinterV2 interval(long interval) {
        daemonPrinterV2.setInterval(interval);
        return daemonPrinterV2;
    }

    public static void run() {

        final String _name = "Daemon-" + Thread.currentThread().getId();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("Interrupted!");
                        break;
                    }

                    System.out.println(String.format("[%s] - [%s] - [%d]", _name,
                            daemonPrinterV2.getClazz().getSimpleName(),
                            System.currentTimeMillis()));

                    try {
                        Thread.sleep(daemonPrinterV2.getInterval());
                    } catch (InterruptedException e) {
                        System.out.println("Interrupted When Sleep");
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        thread.setDaemon(true);
        thread.run();
    }

    private static DaemonPrinterV2 daemonPrinterV2 = new DaemonPrinterV2();

    private Class<?> clazz;
    private long interval;

    public Class<?> getClazz() {
        return clazz;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }

    public long getInterval() {
        return interval;
    }

    public void setInterval(long interval) {
        this.interval = interval;
    }
}
